<template>
<PublicPage :page-name="`${routeData.userType === 'seller'?'退货':'收货'}地址`" :borderType="true" :showNav="true">
  <view class="addressLibrary_layout">
    <scroll-view class="address_list_box" scroll-y="true" -webkit-overflow-scrolling="touch" scroll-with-animation="true">
      <view class="cozy_box" v-if="userAddressList.length>0">
        <image class="img_box" src="https://qqposs.oss-cn-shenzhen.aliyuncs.com/mpAppImg/icon/tips1_icon.png" alt="" />
        温馨提示：长按地址可进行删除
      </view>
      <ul class="address_list_ul" v-if="userAddressList.length>0">
        <li class="address_list_li" v-for="(userItem,userItemIndex) in userAddressList" :key="userItemIndex" @click.stop="choiceAddressFn(userItem)" @longpress='(e) => longPressFn(e,userItem,userItemIndex)'>
          <view class="name_left_box">
            <view class="name_box">{{userItem.name}}</view>
            <span v-if="userItem.isDef==1">默认</span>
          </view>
          <view class="msg_right_box">
            <view class="mobile_box">{{mobileStrFn(userItem.mobile)}}</view>
            <view class="detailedAddress_box">{{userItem.provinceName}}{{userItem.cityName}}{{userItem.countyName}}{{userItem.addr}}</view>
            <view class="u-p-t-20" style="color: #FB9551;" v-if="userItem.isDispatching">超出配送范围</view>
          </view>
          <view class="edit_btn" @click.stop="addAddressFn(1,userItem)" hover-class='hover'>
            <image class="edit_img_box" src="https://qqposs.oss-cn-shenzhen.aliyuncs.com/mpAppImg/icon/edit1_icon.png" alt="" />
          </view>
        </li>
      </ul>
      <view class="not_data_box" v-if="!userAddressList||userAddressList.length<1">
        <image class="notData_img_box" src="https://qqposs.oss-cn-shenzhen.aliyuncs.com/mpAppImg/noneImg/notadderss_icon.png" alt="" />
        <p>暂无{{routeData.userType === 'seller'?'退货':'收货'}}地址</p>
      </view>
    </scroll-view>
    <div class="foot_btn u-flex">
      <button :disabled="disabledBtn" class="btn btn-lf" hover-class='hover' @click.stop="getWxAddress">使用微信地址</button>
      <button class="btn btn-rt" @click.stop="addAddressFn(0)" hover-class='hover'>
        添加{{routeData.userType === 'seller'?'退货':'收货'}}地址
      </button>
    </div>
  </view>
</PublicPage>
</template>
<script>
import PublicPage from "@/components/publicPage/index.vue";
import user from "@/api/user.js"
import Util from "@/api/util.js"
export default {
  components: {
    PublicPage
  },
  data () {
    return {
      isIOS: uni.getSystemInfoSync().system.indexOf("Android") !== 0,
      userAddressList: [],
      routeData: {},
      disabledBtn: false
    }
  },
  onLoad (r) {
    this.routeData = r
  },
  onShow() {
    this.disabledBtn = false
    if(this.routeData.userType === 'seller'){
      this.querySellerAddressListFn()
    }else{
      this.queryAddressListFn()
    }
  },
  methods: {
    choiceAddressFn (data) {
      if (this.routeData.type != 2) return
      this.$store.commit('CHOICE_ADDRESS_DATA', data)
      this.navigateBack({delta: 1
      })
    },
    longPressFn (e,userItem,index) {
      let this_ = this
      wx.showModal({
        title: '提示',
        cancelText: '取消',
        confirmText: '立即删除',
        confirmColor: '#E34D59',
        content: '是否要删除这个地址？',
        success (res) {
          if (res.confirm) {
            user.deleteAddress({id:userItem.id}).then(async (res_) => {
              if (res_.code == 200) {
                if (this_.$store.state.choiceAddressData.id&&userItem.id==this_.$store.state.choiceAddressData.id) {
                  this_.$store.commit('CHOICE_ADDRESS_DATA', {})
                }
                wx.showToast({
                  icon: 'none',
                  mask: true,
                  title: '删除成功!'
                })
                this_.userAddressList.splice(index, 1)
              }
            })
          }
        }
      })
    },
    mobileStrFn (str) {
      return Util.mobileStr(str)
    },
    // 获取买家收货地址
    queryAddressListFn () {
      user.queryUserAddress(this.routeData).then(async (res_) => {
        console.log(res_, 'res_')
        this.userAddressList = res_.data
      })
    },
    // 获取卖家退货地址列表
    querySellerAddressListFn(){
      user.getSellerAddress().then(res => {
        this.userAddressList = res.data
      })
    },
    addAddressFn (type,userItem) {
      if (type==1&&userItem) {
        this.$store.commit('EDIT_ADDRESS_MSG_DATA', userItem)
      }
      this.$store.commit('MAP_DATA', {})
      this.navigateTo({url: `/pagesB/addressLibrary/addAddress?type=${type}&userType=${this.routeData.userType}`})
    },
    // 获取微信地址
    getWxAddress() {
      this.disabledBtn = true
      uni.getSetting({
        success: (res) => {
          if (res.authSetting['scope.address']) {
            // 地址已授权
            uni.authorize({
              scope: 'scope.address',
              success: () => {
                this._chooseAddress()
              }
            })
          } else {
            // 地址未授权--需要拉起设置授权微信地址
            uni.openSetting({
              success: () => {
                this._chooseAddress()
              }
            })
          }
        }
      })
    },
    // 选择微信地址函数
    _chooseAddress() {
      uni.chooseAddress({
        success: (res) => {
          console.log(res, '获取微信地址')
          // 字符串地区id
          const nationalCode = res.nationalCode
          // 根据地区id截取反推省级id
          const provinceCode = nationalCode.slice(0, 2)
          // 根据地区id截取反推城市id
          const cityCode = nationalCode.slice(2, 4)
          const addressObj = {
            addr: res.detailInfo,
            cityId: parseInt(provinceCode + cityCode + '00'),
            countyId: parseInt(nationalCode),
            isDef: this.userAddressList.length ? 0 : 1, // 若原来的地址列表为空时，需要将添加的地址设置为默认地址
            mobile: res.telNumber,
            name: res.userName,
            provinceId: parseInt(provinceCode + '0000'),
            type: this.routeData.userType === 'seller' ? 2 : 1
          }
          // 处理没有地区的城市--例如东莞、中山(只有街道之类的，即6位行政区编码最后两位均为00)
          const countyCode = nationalCode.slice(4, 6)
          if (countyCode === '00') {
            addressObj.countyId = parseInt(res.nationalCodeFull)
          }
          console.log(addressObj, 'addressObj')
          user.addAddress(addressObj).then(result => {
            if (result.code === 200) {
              uni.showToast({
                icon: 'none',
                mask: true,
                title: '地址添加成功!'
              })
              // 若原来的地址列表为空时，将添加的地址添加到vuex中(即默认地址)
              if (!this.userAddressList.length) {
                this.$store.commit('CHOICE_ADDRESS_DATA', result.data)
              }
              // 刷新地址列表
              this.queryAddressListFn()
            }
          })
          // console.log(addressObj)
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.addressLibrary_layout {
  width: 100vw;
  height: 100%;
  background-color: #F2F3F5;
  .address_list_box {
    width: 100%;
    height: calc(100% - 96rpx);
    position: relative;
    .cozy_box {
      padding: 6rpx 32rpx;
      background: #fffbe8;
      font-size: 24rpx;
      color: #FAAB0C;
      display: flex;
      align-items: center;
      margin-bottom: 20rpx;
      .img_box {
        width: 32rpx;
        height: 32rpx;
        margin-right: 8rpx;
      }
    }
    .address_list_ul {
      padding-bottom: 60rpx;
      .address_list_li {
        background-color: #fff;
        padding: 32rpx;
        position: relative;
        display: flex;
        border-bottom: 2rpx solid #ebedf0;
        &:last-child {
          border-bottom: none;
        }
        .name_left_box {
          margin-right: 4rpx;
          .name_box {
            width: 140rpx;
            color: #323233;
            white-space:nowrap;
            overflow:hidden;
            text-overflow:ellipsis;
            margin-bottom: 16rpx;
          }
          span {
            width: 80rpx;
            height: 32rpx;
            border: 2rpx solid #e44435;
            border-radius: 8rpx;
            font-size: 24rpx;
            display: flex;
            justify-content: center;
            align-items: center;
            color: #e44435;
          }
        }
        .msg_right_box {
          width: 450rpx;
          .mobile_box {
            color: #323233;
            margin-bottom: 20rpx;
          }
          .detailedAddress_box {
            width: 100%;
            color: #969799;
            line-height: 40rpx;
            word-break: break-all;
            text-overflow: ellipsis;
            overflow: hidden;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
          }
        }
        .edit_btn {
          position: absolute;
          top: 50%;
          right: 32rpx;
          transform: translateY(-50%);
          .edit_img_box {
            width: 34rpx;
            height: 34rpx;
          }
        }
      }
    }
    .not_data_box {
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%,-50%);
      .notData_img_box {
        width: 320rpx;
        height: 320rpx;
      }
      p {
        color: #969799;
        text-align: center;
      }
    }
  }
  .foot_btn {
    width: 100%;
    .btn {
      width: 50%;
      height: 96rpx;
      line-height: 96rpx;
      font-size: 32rpx;
      text-align: center;
      border-radius: 0;
      color: #fff;
    }
    .btn-lf {
      background-color: $n9Color;
    }
    .btn-rt {
      background: $themeColor;
    }
    .add_btn_box {
      width: 50%;
      height: 88rpx;
      background: #e44435;
      border-radius: 44rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 32rpx;
      color: #fff;
    }
  }
}
</style>
